package com.rainng.coursesystem.service;


import com.rainng.coursesystem.model.CourseResourceItem;
import com.rainng.coursesystem.repository.CourseResourceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;
import java.util.Optional;

@Service
public class CourseResourceService {

    @Autowired
    private CourseResourceRepository CourseResourceRepository;

    String currentDir = System.getProperty("user.dir");
    private String uploadDir= currentDir + "\\src\\main\\resources\\courserrsources";

    // 上传文件并自动添加到资源区
    public String uploadAndAddToCourseResources(MultipartFile file,Long courseId,String type) throws Exception {
        // 使用 UUID 生成唯一的文件 ID
        UUID newFileId = UUID.randomUUID();

        // 检查文件是否已经存在，通过课程 ID 和文件名
        if (CourseResourceRepository.findByCourseIdAndFileName(courseId, file.getOriginalFilename()) != null) {
            throw new Exception("File already in CourseResources");
        }

        // 定义文件的存储路径
        Path copyLocation = Paths.get(uploadDir, newFileId.toString() + "_" + file.getOriginalFilename());
        Files.createDirectories(copyLocation.getParent());  // 确保目录存在
        Files.copy(file.getInputStream(), copyLocation);

        CourseResourceItem item = new CourseResourceItem();
        item.setFileId(newFileId);
        item.setCourseId(courseId);
        item.setFileName(file.getOriginalFilename());
        item.setFileData(copyLocation.toString());  // 存储路径而不是文件内容
        item.setFileType(type);
        CourseResourceRepository.save(item);
        System.out.println(uploadDir);
        return "File uploaded and added to CourseResources successfully!";

    }

    // 根据文件 ID 获取文件
    public CourseResourceItem getCourseResourceById(UUID fileId) {
        return CourseResourceRepository.findById(fileId).orElse(null);
    }

    // 从资源区中移除文件
    public void removeCourseResource(Long CourseId, UUID fileId) throws IOException {
        // 查找要删除的 CourseResourceItem
        Optional<CourseResourceItem> optionalItem = CourseResourceRepository.findByCourseIdAndFileId(CourseId, fileId);

        if (optionalItem.isPresent()) {
            CourseResourceItem item = optionalItem.get(); // 解包 Optional 以获得 CourseResourceItem

            // 删除本地文件
            Path filePath = Paths.get(item.getFileData());
            Files.deleteIfExists(filePath); // 删除文件，如果文件不存在不会抛出异常

            // 从数据库中删除 CourseResourceItem
            CourseResourceRepository.delete(item);
        } else {
            throw new FileNotFoundException("File not found in CourseResources");
        }
    }

    // 获取用户所有收藏
    public List<CourseResourceItem> listCourseResources(Long CourseId, String type) {
        return CourseResourceRepository.findAllByCourseIdAndFileType(CourseId,type);
    }

    // 更新收藏详情
    public boolean updateCourseResource(CourseResourceItem CourseResourceItem) {
        if (CourseResourceRepository.existsById(CourseResourceItem.getFileId())) {
            CourseResourceRepository.save(CourseResourceItem);
            return true;
        }
        return false;
    }

}